// pages/volunteer/address.js
Page({
  data: {
    // 地址列表
    addressList: [
      {
        id: 1,
        name: '张三',
        phone: '13800138000',
        province: '安徽省',
        city: '合肥市',
        district: '蜀山区',
        detail: '政务区天鹅湖路123号',
        isDefault: true
      },
      {
        id: 2,
        name: '李四',
        phone: '13900139000',
        province: '安徽省',
        city: '合肥市',
        district: '包河区',
        detail: '滨湖新区紫云路456号',
        isDefault: false
      }
    ],
    
    // 弹窗状态
    showAddressModal: false,
    editingAddress: null,
    
    // 表单数据
    addressForm: {
      name: '',
      phone: '',
      region: ['安徽省', '合肥市', '蜀山区'],
      detail: '',
      isDefault: false
    }
  },

  onLoad(options) {
    this.loadAddressList();
  },

  onShow() {
    this.refreshData();
  },

  // 加载地址列表
  loadAddressList() {
    const addressList = wx.getStorageSync('volunteerAddresses') || this.data.addressList;
    this.setData({ addressList });
  },

  // 刷新数据
  refreshData() {
    this.loadAddressList();
  },

  // 选择地址
  selectAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    const address = this.data.addressList.find(addr => addr.id === addressId);
    
    if (address) {
      // 返回上一页并传递选中的地址
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      
      if (prevPage && prevPage.setSelectedAddress) {
        prevPage.setSelectedAddress(address);
      }
      
      wx.navigateBack();
    }
  },

  // 设置选中的地址（供其他页面调用）
  setSelectedAddress(address) {
    this.setData({ selectedAddress: address });
  },

  // 添加地址
  addAddress() {
    this.setData({
      showAddressModal: true,
      editingAddress: null,
      addressForm: {
        name: '',
        phone: '',
        region: ['安徽省', '合肥市', '蜀山区'],
        detail: '',
        isDefault: false
      }
    });
  },

  // 编辑地址
  editAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    const address = this.data.addressList.find(addr => addr.id === addressId);
    
    if (address) {
      this.setData({
        showAddressModal: true,
        editingAddress: address,
        addressForm: {
          name: address.name,
          phone: address.phone,
          region: [address.province, address.city, address.district],
          detail: address.detail,
          isDefault: address.isDefault
        }
      });
    }
  },

  // 删除地址
  deleteAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          const addressList = this.data.addressList.filter(addr => addr.id !== addressId);
          this.setData({ addressList });
          wx.setStorageSync('volunteerAddresses', addressList);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 关闭地址弹窗
  closeAddressModal() {
    this.setData({ showAddressModal: false });
  },

  // 表单输入处理
  onNameInput(e) {
    this.setData({
      'addressForm.name': e.detail.value
    });
  },

  onPhoneInput(e) {
    this.setData({
      'addressForm.phone': e.detail.value
    });
  },

  onRegionChange(e) {
    this.setData({
      'addressForm.region': e.detail.value
    });
  },

  onDetailInput(e) {
    this.setData({
      'addressForm.detail': e.detail.value
    });
  },

  onDefaultChange(e) {
    this.setData({
      'addressForm.isDefault': e.detail.value
    });
  },

  // 保存地址
  saveAddress() {
    const { addressForm, editingAddress } = this.data;
    
    // 表单验证
    if (!addressForm.name.trim()) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      });
      return;
    }
    
    if (!addressForm.phone.trim()) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(addressForm.phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      return;
    }
    
    if (!addressForm.detail.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
      return;
    }
    
    let addressList = [...this.data.addressList];
    
    if (editingAddress) {
      // 编辑地址
      const index = addressList.findIndex(addr => addr.id === editingAddress.id);
      if (index !== -1) {
        addressList[index] = {
          ...editingAddress,
          name: addressForm.name,
          phone: addressForm.phone,
          province: addressForm.region[0],
          city: addressForm.region[1],
          district: addressForm.region[2],
          detail: addressForm.detail,
          isDefault: addressForm.isDefault
        };
      }
    } else {
      // 添加新地址
      const newAddress = {
        id: Date.now(),
        name: addressForm.name,
        phone: addressForm.phone,
        province: addressForm.region[0],
        city: addressForm.region[1],
        district: addressForm.region[2],
        detail: addressForm.detail,
        isDefault: addressForm.isDefault
      };
      addressList.push(newAddress);
    }
    
    // 如果设为默认地址，取消其他地址的默认状态
    if (addressForm.isDefault) {
      addressList = addressList.map(addr => ({
        ...addr,
        isDefault: addr.id === (editingAddress ? editingAddress.id : Date.now())
      }));
    }
    
    this.setData({ addressList });
    wx.setStorageSync('volunteerAddresses', addressList);
    
    this.closeAddressModal();
    
    wx.showToast({
      title: editingAddress ? '修改成功' : '添加成功',
      icon: 'success'
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡，防止触发选择地址
  },

  // 返回
  goBack() {
    wx.navigateBack();
  }
});